//
//  NewVersionUtil.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/9/21.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit
 
class NewVersionUtil:UIView {
   
    private var _alertCover = UIView()
 
   func present() {
       let cover = UIView()
       cover.frame = UIScreen.main.bounds
        cover.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.35)
        cover.addSubview(self)
  
       self.snp.makeConstraints { make in
           
           make.center.equalToSuperview()
           make.width.equalTo(KSGlobal.screenW * 0.9)
           make.height.equalTo(self.snp.width).multipliedBy(1.59)
       }
     
       cover.alpha = 0
       self.alpha = 0.5
       if let kwindow =  UIApplication.shared.windows.filter({$0.isKeyWindow}).first {
           kwindow.rootViewController?.view.addSubview(cover)
           cover.layoutIfNeeded()
           self.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
           
           UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseInOut) {
               cover.alpha = 1
               self.alpha = 1
               self.transform = CGAffineTransform.identity
           }
           _alertCover = cover
        }
 
   }
    

   
   func dismiss() {
       UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseInOut) {
           self._alertCover.alpha = 0
       } completion: { isCompleted in
           if isCompleted {
               self.removeFromSuperview()
               self._alertCover.removeFromSuperview()
               KSLog("销毁了")
           }
           KSLog("外面来了")
       }
   }
     var fieldArr = [(String,UITextField)]()
    
    lazy var titleLab:UILabel = {
       let v = UILabel()
         v.textAlignment = .center
        v.font = UIFont.systemFont(ofSize: 18)
        return v
    }()
    lazy var contentLab:UITextView = {
       let v = UITextView()
        v.isUserInteractionEnabled = false
         v.font = UIFont.systemFont(ofSize: 17)
        return v
    }()
    lazy var bgImg:UIImageView = {
       let v = UIImageView()
        v.image = UIImage(named: "newVersionImg")
        return v
    }()
    lazy var upNowBtn:UIButton = {
       let v = UIButton()
        v.setTitle("立即更新", for: .normal)
        v.layer.cornerRadius = 9
        v.backgroundColor = UIColor(kshex: "#E06B35")
        return v
    }()
    lazy var upLaterBtn:UIButton = {
       let v = UIButton()
        v.setTitle("暂不更新", for: .normal)
        v.setTitleColor(.darkGray, for: .normal)
         return v
    }()
    var updatePath = ""
    func add(title:String,message:String ,force:Int ,updatePath:String) {
        self.updatePath = updatePath
        contentLab.text = message
        titleLab.text = title
        if force ==  1 {
            upLaterBtn.isHidden = true
            upNowBtn.snp.remakeConstraints { make in
                make.width.equalTo(220)
                make.height.equalTo(38)
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview().offset(-15)
            }
        } else {
          
        }
 
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
         self.layer.cornerRadius = 5
        self.addSubview(bgImg)
        self.addSubview(titleLab)
         self.addSubview(contentLab)
        self.addSubview(upNowBtn)
        self.addSubview(upLaterBtn)
        bgImg.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        titleLab.snp.makeConstraints { make in
           make.top.equalTo(self.snp.centerY).offset(-38)
           make.centerX.equalToSuperview()
           make.width.equalToSuperview().multipliedBy(0.9)
           }
          contentLab.snp.makeConstraints { make in
             make.top.equalTo(titleLab.snp.bottom).offset(6)
             make.centerX.equalToSuperview()
             make.width.equalToSuperview().multipliedBy(0.8)
             make.bottom.equalTo(upNowBtn.snp.top).offset(-10)
            }
        upNowBtn.snp.makeConstraints { make in
            make.width.equalTo(220)
            make.height.equalTo(38)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-54)
        }
        upLaterBtn.snp.makeConstraints { make in
            make.width.equalTo(220)
            make.height.equalTo(38)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-8)
        }
        upNowBtn.addTouchUpInSideAction { _ in
            if let papa = URL(string: self.updatePath) {
                UIApplication.shared.open(papa, options: [:], completionHandler: nil)
                TOKEN = ""
            } else {
                self.dismiss()
                KSToast("更新路径配置有误")
            }
        }
        upLaterBtn.addTouchUpInSideAction { _ in
            self.dismiss()
        }
   
      }
     required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

    
    
}





protocol updateAlertable: AnyObject {
    
    func updateVersionTool(controller:UIViewController,localVersion:String?,remoteVersion:String?,updatePath:String,force:Int?,content:String?)
    
}
// 版本更新协议
extension updateAlertable {
    //  localVersion 本地版本   remoteVersion 线上配置版本  updatePath 更新路径url  force 强制更新标识  content 更新内容
    func updateVersionTool(controller:UIViewController,localVersion:String?,remoteVersion:String?,updatePath:String,force:Int? = 0,content:String? = "") {
        KSLog("本地与线上版本")
        KSLog("\(localVersion)----\(remoteVersion)")
        if let local = localVersion,let remote = remoteVersion {
            
            if  remoteLargeThanLocal(local: local, remote: remote) {
                
                
                let descStr = content.unwrap.replacingOccurrences(of: "#", with: "\n")
                let vvv = NewVersionUtil()
                vvv.add( title:"新版本\(remote)可更新",message: "\(descStr)",force: force.intWrap,updatePath: updatePath)
                vvv.present()
                
                
                
                
                
                 
                
            }
            
        }
        
    }
    
}

/// 比较版本的大小    服务端大于本地  返回 true   否则 返回false     版本号固定为三位 (之前用字符串比较，上了两位数有bug)
func remoteLargeThanLocal(local:String,remote:String) -> Bool {
    KSLog("本地与线上版本2")
    KSLog("\(local)----\(remote)")
    let loArr = local.components(separatedBy: ".")
    let reArr = remote.components(separatedBy: ".")
    
    let intLoArr = loArr.compactMap { Int($0) }
    let intReArr = reArr.compactMap { Int($0) }
    
    guard intLoArr.count == 3, intReArr.count == 3 else {
        print("版本配置有误，\(local),\(remote)")
        return false
    }
    let joinLo = intLoArr[0] * 10000 + intLoArr[1] * 100 + intLoArr[2]
    let joinRe = intReArr[0] * 10000 + intReArr[1] * 100 + intReArr[2]
    
    return joinRe > joinLo
}
